<template>
  <div class="wrap">
    <template v-if="tabAct === 1">
      <div class="set_pwd">
        <div class="title">账号验证</div>
        <div class="remark">通过验证码校验后进行密码的重置</div>
        <div class="phone">{{ phoneDesensitize(username) }}</div>
        <Button :styles="{ width:'620rpx',height:'80rpx',borderRadius: '47rpx',fontSize:'36rpx' }" class="footer" @confirm="sendVerificationCode">
          发送验证码
        </Button>
      </div>
    </template>
    <template v-else-if="tabAct === 2">
      <div class="code_form">
        <div class="code_title">输入验证码</div>
        <div class="code_tips">验证码已发送至+86 {{ username }}</div>
        <div class="code_box">
          <VCode @code="password = $event" />
        </div>
        <div
          :style="{color: codeTime === 60 ? '#ff8002' : 'rgba(0, 0, 0, 0.45)'}"
          class="code_get"
          @tap="getVCdoe"
        >
          {{ getVCodeBtn }}
        </div>
      </div>
    </template>
    <template v-else>
      <div class="set_pwd">
        <div class="title">重置密码</div>
        <div class="remark remark1">请输入8位以上的字母加数字的密码组合</div>
        <u--form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="0"
        >
          <u-form-item prop="newPassword1">
            <u--input
              v-if="isPassword"
              v-model="form.newPassword1"
              :custom-style="{paddingLeft: 0}"
              border="bottom"
              maxlength="16"
              placeholder="请填写新的密码"
              type="password"
            >
              <template #suffix>
                <Icon :styles="{opacity: '0.25'}" name="icon-biyanjing" size="40" @tap.stop="isPassword= !isPassword" />
              </template>
            </u--input>
            <u--input
              v-else
              v-model="form.newPassword1"
              :custom-style="{paddingLeft: 0}"
              border="bottom"
              maxlength="16"
              placeholder="请填写新的密码"
              type="text"
            >
              <template #suffix>
                <Icon :styles="{opacity: '0.25'}" name="icon-yanjing" size="40" @tap.stop="isPassword= !isPassword" />
              </template>
            </u--input>
          </u-form-item>
          <u-form-item prop="newPassword2">
            <u--input
              v-if="isPassword1"
              v-model="form.newPassword2"
              :custom-style="{paddingLeft: 0}"
              border="bottom"
              maxlength="16"
              placeholder="请再次输入密码"
              type="password"
            >
              <template #suffix>
                <Icon :styles="{opacity: '0.25'}" name="icon-biyanjing" size="40" @tap.stop="isPassword1 = !isPassword1" />
              </template>
            </u--input>
            <u--input
              v-else
              v-model="form.newPassword2"
              :custom-style="{paddingLeft: 0}"
              border="bottom"
              maxlength="16"
              placeholder="请再次输入密码"
              type="text"
            >
              <template #suffix>
                <Icon :styles="{opacity: '0.25'}" name="icon-yanjing" size="40" @tap.stop="isPassword1 = !isPassword1" />
              </template>
            </u--input>
          </u-form-item>
        </u--form>
        <Button :styles="{ width:'620rpx',height:'80rpx',borderRadius: '47rpx',fontSize:'36rpx' }" class="footer" @confirm="savePwd">
          保存新密码
        </Button>
      </div>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue'
import Button from '@C/Button.vue'
import { Msg, MsgLoading, MsgLoadingClear } from '@C/Msg'
import { onShow, LStorage, Router, phoneDesensitize, storeState } from '@U/common'
import { RegText } from '@U/regular'
import VCode from '@C/VCodeKeyBoard.vue'
import Icon from '@C/Icon.vue'
import { clearToken } from '@U/Auth'
import { checkUpdatePwdSms, updatePwd, sendUpdatePwdSms } from './request'
import type { IFunc } from '@/interface'

const isPassword = ref(true)
const isPassword1 = ref(true)
const rules = {
  newPassword1: [
    {
      required: true,
      message: '新密码不能为空',
      trigger: 'blur',
    },
    {
      validator: (rule: any, value: any, callback: IFunc) => {
        if (!RegText('密码', value)) {
          callback('密码必须包含数字、字母的组合，长度不能低于8位')
        } else {
          // 如果校验通过，也要执行callback()回调
          callback()
        }
      },
    },
  ],
  newPassword2: [
    {
      required: true,
      message: '请再次输入新密码',
      trigger: 'blur',
    },
    {
      validator: (rule: any, value: any, callback: IFunc) => {
        if (form.newPassword1 !== form.newPassword2) {
          callback('两次输入密码不一致')
        } else {
          // 如果校验通过，也要执行callback()回调
          callback()
        }
      },
    },
  ],
}
const username = ref('')
// 账号获取
function getUsername() {
  username.value = storeState.zhiKeInfo?.mobile
}
const tabAct = ref(1)

// 验证码倒计时
const codeTime = ref(59)
const codeTimer = ref()
// 获取验证码
const getVCodeBtn = computed(() => `${codeTime.value !== 60 ? `${codeTime.value}s 后可重新获取` : '获取验证码'}`)
const getVCdoe = async () => {
  if (getVCodeBtn.value === '获取验证码') {
    await MsgLoading()
    await getSendSms()
  }
}
const getSendSms = async () => {
  await MsgLoading()
  const { code, msg } = await sendUpdatePwdSms().finally(() => {})
  if (code === 200) {
    uni.hideLoading()
    Msg({ icon: 'success', msg: '已发送' })
    tabAct.value = 2
    codeTimer.value = setInterval(() => {
      --codeTime.value
      if (codeTime.value < 1) {
        codeTime.value = 60
        clearInterval(codeTimer.value)
      }
    }, 1000)
  } else {
    clearInterval(codeTimer.value)
    codeTime.value = 60
    Msg({ icon: 'error', msg })
  }
}

// 发送验证码
const sendVerificationCode = async () => {
  await getSendSms()
}

const password = ref('')
// 重置密码
const form = reactive({
  newPassword1: '',
  newPassword2: '',
})

const flag = ref(false)

const formRef = ref()
// 保存密码
const savePwd = () => {
  formRef.value.validate().then(async () => {
    if (!flag.value) {
      flag.value = true
      await MsgLoading()
      const { code, msg } = await updatePwd(form.newPassword1).finally(() => {
        MsgLoadingClear()
        flag.value = false
      })
      if (code === 200) {
        Msg({ icon: 'success', msg: '保存成功' })
        setTimeout(() => {
          clearToken()
          Router.reLaunch('login')
        }, 1000)
      } else {
        Msg({ icon: 'error', msg })
      }
    }
  }).catch((err: any) => {
    console.log(err)
  })
}

watch(
    () => password.value,
    async () => {
      if (!password.value.length) return false
      if (password.value.length === 6) {
        await checkUpdatePwdSms(password.value)
        tabAct.value = 3
      }
    },
)
onShow(() => {
  getUsername()
})
</script>

<style lang="less" scoped>
.wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 242rpx 66rpx 60rpx;
  background: white;
  .set_pwd {
    flex: 1 1;
    width: 100%;
    .title {
      color: rgba(0,0,0,0.85);
      font-size: 48rpx;
      font-weight: 400;
    }
    .remark{
      color: rgba(0,0,0,0.45);
      margin-top: 10rpx;
      font-size: 28rpx;
    }
    .phone {
      font-size: 64rpx;
      font-weight: 600;
      color: #262626;
      line-height: 90rpx;
      margin-top: 58rpx;
    }
    .remark1 {
      margin-bottom: 64rpx;
    }
    .footer{
      margin-top: 100rpx;
    }
  }
  .code_form {
    flex: 1 1;
    width: 100%;
    .code_title {
      width: 100%;
      height: 66rpx;
      font-size: 48rpx;
      opacity: 0.85;
      margin-bottom: 2rpx;
    }
    .code_tips {
      width: 100%;
      height: 34rpx;
      margin-bottom: 52rpx;
      font-size: 28rpx;
      opacity: 0.45;
    }
    .code_box {
      height: 85rpx;
      margin-bottom: 46rpx;
    }
  }
  .code_get {
    height: 34rpx;
    color: rgba(0, 0, 0, 0.45);
    font-size: 28rpx;
  }
  ::v-deep .is-input-border {
    border-top: none;
    border-left: none;
    border-right: none;
  }
}
</style>
